const api = require('../../utils/api')

Page({
  data: {
    currentYear: new Date().getFullYear(),
    currentMonth: new Date().getMonth() + 1,
    groupedRecords: [],
    currentType: 'glucose', // glucose, bloodPressure, weight
    isMonthExpanded: false
  },

  onLoad(options) {
    // 如果有传入type参数，则设置当前类型
    if (options && options.type) {
      this.setData({
        currentType: options.type
      })
    }
    this.fetchRecords()
  },

  async fetchRecords() {
    try {
      console.log('开始获取记录数据，当前类型:', this.data.currentType)
      
      const startDate = new Date(this.data.currentYear, this.data.currentMonth - 1, 1).toISOString()
      const endDate = new Date(this.data.currentYear, this.data.currentMonth, 0).toISOString()
      console.log('获取数据的日期范围:', startDate, '至', endDate)
      
      const records = await api.health.getRecords({
        type: this.data.currentType, // 使用当前选择的类型
        // 获取当月数据
        startDate: startDate,
        endDate: endDate
      })

      console.log('获取到的记录数据:', records, '记录数量:', records ? records.length : 0)

      // 处理数据，添加日期分组
      const processedRecords = this.processRecords(records)
      
      console.log('处理后的分组数据:', processedRecords)
      
      this.setData({
        groupedRecords: processedRecords
      })
    } catch (err) {
      console.error('获取记录失败:', err)
      wx.showToast({
        title: '获取数据失败',
        icon: 'none'
      })
    }
  },

  processRecords(records) {
    if (!records || records.length === 0) return []
    
    // 按日期重新组织数据
    const groups = {}
    
    records.forEach(record => {
      // 检查并处理时间戳
      let timestamp = record.timestamp;
      
      // 如果有measuredAt但没有timestamp，转换measuredAt为时间戳
      if (!timestamp && record.measuredAt) {
        timestamp = new Date(record.measuredAt).getTime();
      }
      
      // 确保时间戳是有效的数字
      if (!timestamp || isNaN(timestamp)) {
        console.warn('无效的时间戳', record);
        timestamp = Date.now(); // 使用当前时间作为后备
        record.timestamp = timestamp;
      }
      
      const date = new Date(timestamp)
      const dateStr = `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
      
      if (!groups[dateStr]) {
        groups[dateStr] = {
          dateStr: dateStr,
          expanded: false,
          records: [],
          date: date.toISOString().split('T')[0] // 添加日期标识，用于比较
        }
      }
      
      groups[dateStr].records.push({
        ...record,
        timestamp: timestamp, // 确保使用处理后的时间戳
        timeStr: this.formatTime(timestamp),
        dateStr: dateStr
      })
    })
    
    // 按日期降序排序
    const sortedGroups = Object.values(groups).sort((a, b) => {
      return new Date(b.date) - new Date(a.date);
    });
    
    return sortedGroups;
  },

  formatTime(timestamp) {
    const date = new Date(timestamp)
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    return `${hours}:${minutes}`
  },

  changeType(e) {
    const type = e.currentTarget.dataset.type
    this.setData({ currentType: type }, () => {
      this.fetchRecords()
    })
  },

  // 长按记录
  onLongPressRecord(e) {
    const { timestamp, record } = e.currentTarget.dataset
    const that = this

    wx.showActionSheet({
      itemList: ['编辑', '删除'],
      success(res) {
        if (res.tapIndex === 0) {
          // 编辑记录
          that.editRecord(timestamp, record)
        } else if (res.tapIndex === 1) {
          // 删除记录
          that.confirmDeleteRecord(timestamp)
        }
      }
    })
  },

  // 弹出确认删除对话框
  confirmDeleteRecord(timestamp) {
    const that = this
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条记录吗？',
      confirmColor: '#FF3B30',
      success(res) {
        if (res.confirm) {
          that.deleteRecord(timestamp)
        }
      }
    })
  },

  // 删除记录
  async deleteRecord(timestamp) {
    try {
      console.log('准备删除记录，时间戳:', timestamp);
      
      // 根据record对象的数据结构决定使用哪个字段作为ID
      let recordId = timestamp;
      
      // 如果需要，先获取完整记录信息
      const fullRecord = await api.health.getRecordByTimestamp(this.data.currentType, timestamp);
      if (fullRecord && fullRecord._id) {
        console.log('获取到完整记录:', fullRecord);
        recordId = fullRecord._id; // 优先使用记录的_id
      } else {
        console.log('未找到完整记录，使用时间戳作为ID');
      }
      
      const result = await api.health.deleteRecord(this.data.currentType, recordId);
      if (result) {
        // 刷新当前页面数据
        this.fetchRecords();
        
        // 显示成功提示
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
        
        // 尝试通知前一个页面刷新数据
        try {
          console.log('准备通知前一页面数据已删除');
          
          // 通过页面栈设置刷新标志
          const pages = getCurrentPages();
          pages.forEach(page => {
            if (page.route.includes('bloodsugardetail') || 
                page.route.includes('bloodpressuredetail') || 
                page.route.includes('weightdetail')) {
              if (typeof page.setData === 'function') {
                console.log(`设置页面 ${page.route} 的刷新标志`);
                page.setData({ 
                  needRefresh: true,
                  lastFetchTime: null
                });
                
                // 清除页面缓存
                if (typeof page.clearAllCache === 'function') {
                  page.clearAllCache();
                }
                
                // 立即触发刷新
                if (typeof page.fetchData === 'function') {
                  setTimeout(() => page.fetchData(), 100);
                }
              }
            }
          });
          
          // 通过事件通道通知上一个页面
          const eventChannel = this.getOpenerEventChannel();
          if (eventChannel && typeof eventChannel.emit === 'function') {
            console.log('通过事件通道通知前一页面数据已删除');
            eventChannel.emit('dataChanged', { 
              type: this.data.currentType,
              action: 'delete',
              timestamp: new Date().getTime()
            });
          }
        } catch (error) {
          console.error('通知数据更新失败:', error);
        }
      } else {
        wx.showToast({
          title: '删除失败',
          icon: 'none'
        });
      }
    } catch (err) {
      console.error('删除记录失败:', err);
      wx.showToast({
        title: '删除失败，请重试',
        icon: 'none'
      });
    }
  },

  // 编辑记录
  editRecord(timestamp, record) {
    console.log('准备编辑记录:', { timestamp, record });
    
    // 根据不同类型数据，导航到不同的编辑页面
    let url = '';
    if (this.data.currentType === 'bloodPressure') {
      url = `/pages/record/record?type=bloodPressure&isEditMode=true&timestamp=${timestamp}&id=${record._id || timestamp}`;
    } else if (this.data.currentType === 'glucose') {
      url = `/pages/record/record?type=glucose&isEditMode=true&timestamp=${timestamp}&id=${record._id || timestamp}`;
    } else if (this.data.currentType === 'weight') {
      url = `/pages/record/record?type=weight&isEditMode=true&timestamp=${timestamp}&id=${record._id || timestamp}`;
    }
    
    wx.navigateTo({
      url: url,
      events: {
        recordAdded: (data) => {
          console.log('记录编辑成功:', data);
          this.fetchRecords(); // 记录更新后刷新列表
        }
      },
      success: (res) => {
        // 添加额外数据传递
        res.eventChannel.emit('editRecord', { record });
      }
    });
  },

  goToDetail(e) {
    const { type } = e.currentTarget.dataset
    const pages = {
      glucose: '/pages/bloodsugardetail/bloodsugardetail',
      bloodPressure: '/pages/bloodPressureDetail/bloodPressureDetail',
      weight: '/pages/weightDetail/weightDetail'
    }
    if (pages[type]) {
      wx.navigateTo({
        url: pages[type]
      })
    }
  },

  toggleMonth() {
    // 如果要收起月视图，不需要处理组内展开状态
    if (this.data.isMonthExpanded) {
      this.setData({
        isMonthExpanded: false
      })
      return
    }
    
    // 准备关闭所有已展开的分组
    const closedGroups = {}
    this.data.groupedRecords.forEach((group, i) => {
      if (group.expanded) {
        closedGroups[`groupedRecords[${i}].expanded`] = false
      }
    })
    
    // 展开月视图，同时确保所有日期组都是收起的
    this.setData({
      isMonthExpanded: true,
      ...closedGroups
    })
  },

  toggleGroup(e) {
    if (!this.data.isMonthExpanded) return
    const date = e.currentTarget.dataset.date
    const index = this.data.groupedRecords.findIndex(group => group.date === date)
    
    if (index === -1) return
    
    // 找到当前项的展开状态
    const currentExpanded = this.data.groupedRecords[index].expanded
    
    // 关闭所有组
    const closedGroups = {}
    this.data.groupedRecords.forEach((group, i) => {
      if (group.expanded) {
        closedGroups[`groupedRecords[${i}].expanded`] = false
      }
    })
    
    // 只更新需要变化的状态，减少渲染工作量
    this.setData({
      ...closedGroups,
      [`groupedRecords[${index}].expanded`]: !currentExpanded
    })
  },

  // 确认删除全部记录
  confirmDeleteAll() {
    const that = this
    const recordType = this.data.currentType === 'glucose' ? '血糖' : 
                       this.data.currentType === 'bloodPressure' ? '血压' : '体重'
    
    // 第一层确认
    wx.showModal({
      title: '删除确认',
      content: `确定要删除全部${recordType}记录吗？此操作不可恢复！`,
      confirmColor: '#FF3B30',
      success(res) {
        if (res.confirm) {
          // 第二层确认，要求用户输入"确认删除"
          wx.showModal({
            title: '为防止误操作，请输入"确认删除"',
            content: '',
            confirmColor: '#FF3B30',
            editable: true,
            placeholderText: '',
            success(res) {
              if (res.confirm) {
                // 验证输入，支持中英文确认（忽略大小写）
                const userInput = res.content || '';
                const isValidChinese = userInput === '确认删除';
                const isValidEnglish = userInput.toLowerCase() === 'confirm delete' || 
                                       userInput.toLowerCase() === 'confirmdelete';
                
                if (isValidChinese || isValidEnglish) {
                  that.deleteAllRecords();
                } else {
                  // 输入不匹配
                  wx.showToast({
                    title: '输入不正确，操作取消',
                    icon: 'none'
                  });
                }
              }
            }
          })
        }
      }
    })
  },

  // 执行删除全部记录
  /**
   * 删除当前选中类型的所有健康记录
   * 该方法通过批量删除API一次性删除当月所有数据
   * 删除后会更新UI并通知其他相关页面刷新数据
   */
  async deleteAllRecords() {
    try {
      // 获取当前月份的所有记录
      const startDate = new Date(this.data.currentYear, this.data.currentMonth - 1, 1).toISOString()
      const endDate = new Date(this.data.currentYear, this.data.currentMonth, 0).toISOString()
      
      const records = await api.health.getRecords({
        type: this.data.currentType,
        startDate: startDate,
        endDate: endDate
      })
      
      // 如果没有记录，显示提示并退出
      if (!records || records.length === 0) {
        wx.showToast({
          title: '没有记录可删除',
          icon: 'none'
        })
        return
      }
      
      // 显示加载提示
      wx.showLoading({
        title: '删除中...',
        mask: true
      })
      
      // 使用批量删除API
      const result = await api.health.batchDeleteRecords(this.data.currentType, records);
      
      // 隐藏加载提示
      wx.hideLoading()
      
      // 刷新列表
      this.fetchRecords()
      
      // 显示结果提示
      if (result.success && result.failCount === 0) {
        wx.showToast({
          title: `成功删除${result.successCount}条记录`,
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: `成功${result.successCount}条，失败${result.failCount}条`,
          icon: 'none'
        })
      }
      
      // 尝试通知前一个页面刷新数据
      try {
        console.log('准备通知前一页面数据已删除');
        
        // 通过页面栈设置刷新标志
        const pages = getCurrentPages();
        pages.forEach(page => {
          // 判断是否为健康详情页面
          if (page.route.includes('bloodsugardetail') || 
              page.route.includes('bloodpressuredetail') || 
              page.route.includes('weightdetail')) {
            if (typeof page.setData === 'function') {
              console.log(`设置页面 ${page.route} 的刷新标志`);
              // 通知页面数据需要刷新
              page.setData({ 
                needRefresh: true,
                lastFetchTime: null
              });
              
              // 清除页面缓存
              if (typeof page.clearAllCache === 'function') {
                page.clearAllCache();
              }
              
              // 立即触发刷新 - 使用setTimeout避免阻塞当前操作
              if (typeof page.fetchData === 'function') {
                setTimeout(() => page.fetchData(), 100);
              }
            }
          }
        });
      } catch (err) {
        console.error('通知数据更新失败:', err);
      }
    } catch (err) {
      console.error('删除全部记录失败:', err)
      wx.hideLoading()
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      })
    }
  }
})